//
//  HMStatusViewModel.swift
//  MicroBlog
//
//  Created by Apple on 16/9/23.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
import YYText
//封装微博首页自定义cell业务逻辑处理-->首页cell
class HMStatusViewModel: NSObject {
    //微博模型对象
    var status: HMStatus?
    //提供会员等级图片
    var mbrankImage: UIImage?
    //转发数
    var retweetCountContent: String?
    //评论数
    var commentCountContent: String?
    //赞
    var unlikeCountContent: String?
    //转发微博的内容
    var retweetContent: String?
    //认证类型图片
    var verifiedTypeImage: UIImage?
    //数据来源
    var sourceContent: String?
    /*
     时间格式化逻辑
     是否是今年
     是否是今天
     是否是1分钟之内
     刚刚
     是否是1小时之内
     xx分钟前
     否则
     xx小时前
     是否是昨天
     昨天 10:21
     其他
     11-21 11:11
     不是今年
     2015-10-21 10:10
     */
    //时间
    var timeContent: String? {
        //获取时间字符串
        guard let creatAt = status?.created_at else {
            return nil
        }
        return Date.sinaDate(createAt: creatAt).sinaDateString
    }
    
    //原创微博富文本
    var originalAttributedString: NSAttributedString?
    //转发微博富文本
    var retweetAttributedString: NSAttributedString?
    
    init(status: HMStatus) {
        super.init()
        //获取微博数据
        self.status = status
        //处理业务逻辑
        handleMbrankImage(mbrank: status.user?.mbrank ?? 0)
        //处理按钮上显示内容
        retweetCountContent = handleCountContent(count: status.reposts_count, defaultTitle: "转发")
        commentCountContent = handleCountContent(count: status.comments_count, defaultTitle: "评论")
        unlikeCountContent = handleCountContent(count: status.attitudes_count, defaultTitle: "赞")
        //转发微博
        handleReweetContent(status: status)
        //认证等级
        handleVerifiedTypeImage(VerifiedType: status.user?.verified_type ?? 0)
        //来源
        handleSource(source: status.source ?? "")
        //原创微博富文本
        originalAttributedString = handleStatusAttributedStr(status: status.text!, isretweet: false)
    }
    
    //根据正则匹配表情描述字符串->转成富文本
    private func handleStatusAttributedStr(status: String, isretweet: Bool) -> NSAttributedString{
        //微博字符串转成富文本
        let resultAttributedString = NSMutableAttributedString(string: status)
        let matchResult = try! NSRegularExpression(pattern: "\\[\\w+\\]", options: []).matches(in: status, options: [], range: NSMakeRange(0, (status as NSString).length))
        for match in matchResult.reversed() {
            let range = match.range
            let chs = (status as NSString).substring(with: range)
            //通过表情描述查找表情模型
            if let emoticon = HMEmoticonTools.shareTools.selectedEmoticon(chs: chs) {
                //有对应的表情模型,表情文字大小
                //                let attributedStr = NSAttributedString.attributedStringWithEmoticon(emoticon: emoticon, font: UIFont.systemFont(ofSize: HMHomeTableViewCellFontSize))
                //根据路径创建UIImage对象
                let image = UIImage(named: emoticon.path!)
                //使用YYText创建富文本表情
                let attributedStr = NSAttributedString.yy_attachmentString(withEmojiImage: image!, fontSize: HMHomeTableViewCellFontSize)
                //根据指定范围替换成表情富文本
                resultAttributedString.replaceCharacters(in: range, with: attributedStr!)
                
            }
        }
        //富文本字体大小
        resultAttributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: HMHomeTableViewCellFontSize), range: NSMakeRange(0, resultAttributedString.length))
        if isretweet {
            //转发富文本颜色
            resultAttributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGray, range: NSMakeRange(0, resultAttributedString.length))
        } else {
            //原创富文本颜色
            resultAttributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGray, range: NSMakeRange(0, resultAttributedString.length))
        }
        //匹配高亮文字范围 @xxx:
        addHighlightedAttributedString(regular: "@\\w+", resultAttributedString: resultAttributedString)
        //匹配话题
        addHighlightedAttributedString(regular: "#[^#]+#", resultAttributedString: resultAttributedString)
        //匹配链接
        addHighlightedAttributedString(regular: "http[s]?://[^\\s\\u4e00-\\u9fa5]+", resultAttributedString: resultAttributedString)
        return resultAttributedString
    }
    
    //添加高亮效果的属性
    private func addHighlightedAttributedString(regular:String, resultAttributedString: NSMutableAttributedString) {
        //匹配高亮文字范围 @xxx:
        //获取富文本对应的字符串
        let text = resultAttributedString.string
        let matchHighLightedResult = try! NSRegularExpression(pattern: regular, options: []).matches(in: text, options: [], range: NSMakeRange(0, (text as NSString).length))
        for matchHighlighted in matchHighLightedResult {
            let range = matchHighlighted.range
            //前景颜色
            let color = UIColor(red: 80 / 255, green: 125 / 255, blue: 215 / 255, alpha: 1)
            resultAttributedString.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
            let textHighlight = YYTextHighlight()
            //点击高亮颜色
            let bgColor = UIColor(red: 177 / 255, green: 215 / 255, blue: 255 / 255, alpha: 1)
            //背景边框对象
            let border = YYTextBorder(fill: bgColor, cornerRadius: 3)
            //边框内间距
            border.insets = UIEdgeInsets(top: 1, left: 0, bottom: 0, right: 0)
            textHighlight.setBackgroundBorder(border)
            //设置高亮效果,使用yytext
            resultAttributedString.yy_setTextHighlight(textHighlight, range: range)
        }
    }
    
    //处理认证类型等级图片逻辑
    private func handleVerifiedTypeImage(VerifiedType: Int) {
        switch VerifiedType {
        case 1:
            verifiedTypeImage = UIImage(named: "avatar_vip")
        case 2,3,5:
            verifiedTypeImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedTypeImage = UIImage(named: "avatar_grassroot")
        default:
            verifiedTypeImage = nil
        }
    }
    //处理来源数据
    private func handleSource(source: String) {
        print(source)
        //<a href="http://app.weibo.com/t/feed/4fuyNj" rel="nofollow">即刻笔记</a>
        //判断字符串是否有包含特定的字符串
        if source.contains("\">") && source.contains("</"){
            //说明来源有内容,截取特定字符串
            let startRange = source.range(of: "\">")!
            let endRange = source.range(of: "</")!
            //光标的上限索引
            let startIndex = startRange.upperBound
            //光标的下限索引
            let endIndex = endRange.lowerBound
            sourceContent = "来自:" + source.substring(with: startIndex..<endIndex)
        }
    }
    //处理会员等级图片的逻辑
    private func handleMbrankImage(mbrank: Int) {
        //判断数据是否在1-6之间
        if mbrank >= 1 && mbrank <= 6 {
            mbrankImage = UIImage(named: "common_icon_membership_level\(mbrank)")
        }
    }
    
    //处理转发,评论,赞数据显示的逻辑
    private func handleCountContent(count: Int, defaultTitle: String) -> String{
        if count > 0{
            return "\(count)"
        } else {
            return defaultTitle
        }
    }
    
    //处理转发微博内容
    private func handleReweetContent(status: HMStatus) {
        if status.retweeted_status != nil {
            //1.获取转发微博的用户名
            let name = status.retweeted_status?.user?.screen_name
            //2.获取转发微博的内容
            let retweetText = status.retweeted_status?.text
            //判断用户名和转发内容是否为空
            if name != nil && retweetText != nil {
                retweetContent = "@\(name!):\(retweetText!)"
                //处理转发微博富文本
                retweetAttributedString = handleStatusAttributedStr(status: retweetContent!, isretweet: true)
            }
        }
    }
}
